<template>
  <div class="recommendation-view">
    <div class="page-header">
      <h2>智能推荐</h2>
      <p>基于天气、场合、个人偏好的智能搭配推荐</p>
    </div>

    <!-- 位置状态组件 -->
    <LocationStatus
      :location="userLocation"
      :loading="locationLoading"
      :error="locationError"
      @refresh="handleLocationRefresh"
    />

    <!-- 天气信息卡片 -->
    <el-card class="weather-card" v-if="weatherInfo">
      <template #header>
        <div class="weather-header">
          <el-icon><Sunny /></el-icon>
          <div class="location-info">
            <span class="city-name" v-if="weatherInfo.city">{{ weatherInfo.city }} 天气</span>
            <span v-if="userLocation" class="location-detail">
              {{ userLocation.address }}
              <el-tag size="small" type="info">{{ userLocation.source === 'gps' ? 'GPS' : userLocation.source === 'ip' ? 'IP定位' : '默认' }}</el-tag>
            </span>
          </div>
          <div class="weather-actions">
            <el-button
              size="small"
              @click="refreshLocation"
              :loading="locationLoading"
              title="重新定位"
            >
              <el-icon><Location /></el-icon>
            </el-button>
            <el-button
              size="small"
              @click="refreshWeather"
              :loading="weatherLoading"
              title="刷新天气"
            >
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <div class="weather-content">
        <div class="weather-main">
          <div class="temperature">{{ weatherInfo.temperature }}°C</div>
          <div class="condition">{{ weatherInfo.condition }}</div>
          <div class="feels-like">体感温度 {{ weatherInfo.feelsLike }}°C</div>
        </div>
        <div class="weather-details">
          <div class="detail-item">
            <span class="label">湿度</span>
            <span class="value">{{ weatherInfo.humidity }}%</span>
          </div>
          <div class="detail-item">
            <span class="label">风速</span>
            <span class="value">{{ weatherInfo.windSpeed }} km/h</span>
          </div>
        </div>
      </div>

      <div class="weather-mock" v-if="weatherInfo.isMock">
        <el-alert
          title="当前显示模拟天气数据，可配置真实天气API"
          type="info"
          :closable="false"
          show-icon
        />
      </div>
    </el-card>

    <!-- 推荐类型选择 -->
    <el-card class="recommendation-types">
      <template #header>
        <span>推荐类型</span>
      </template>

      <el-row :gutter="16">
        <el-col :span="4">
          <el-card
            class="type-card compact"
            :class="{ active: activeType === 'smart' }"
            @click="setActiveType('smart')"
            shadow="hover"
          >
            <div class="type-content">
              <el-icon class="type-icon"><MagicStick /></el-icon>
              <h4>智能推荐</h4>
              <p>综合天气和偏好</p>
            </div>
          </el-card>
        </el-col>

        <el-col :span="4">
          <el-card
            class="type-card compact"
            :class="{ active: activeType === 'today' }"
            @click="setActiveType('today')"
            shadow="hover"
          >
            <div class="type-content">
              <el-icon class="type-icon"><Calendar /></el-icon>
              <h4>今日推荐</h4>
              <p>今天特别推荐</p>
            </div>
          </el-card>
        </el-col>

        <el-col :span="4">
          <el-card
            class="type-card compact"
            :class="{ active: activeType === 'weather' }"
            @click="setActiveType('weather')"
            shadow="hover"
          >
            <div class="type-content">
              <el-icon class="type-icon"><Sunny /></el-icon>
              <h4>天气推荐</h4>
              <p>根据天气推荐</p>
            </div>
          </el-card>
        </el-col>

        <el-col :span="4">
          <el-card
            class="type-card compact"
            :class="{ active: activeType === 'occasion' }"
            @click="setActiveType('occasion')"
            shadow="hover"
          >
            <div class="type-content">
              <el-icon class="type-icon"><OfficeBuilding /></el-icon>
              <h4>场合推荐</h4>
              <p>不同场合搭配</p>
            </div>
          </el-card>
        </el-col>

        <el-col :span="4">
          <el-card
            class="type-card compact"
            :class="{ active: activeType === 'color' }"
            @click="setActiveType('color')"
            shadow="hover"
          >
            <div class="type-content">
              <el-icon class="type-icon"><Brush /></el-icon>
              <h4>颜色搭配</h4>
              <p>颜色理论搭配</p>
            </div>
          </el-card>
        </el-col>

        <el-col :span="4">
          <el-card
            class="type-card compact"
            :class="{ active: activeType === 'ai' }"
            @click="setActiveType('ai')"
            shadow="hover"
          >
            <div class="type-content">
              <el-icon class="type-icon"><MagicStick /></el-icon>
              <h4>AI分析</h4>
              <p>免费AI推荐</p>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 第二行推荐类型 -->
      <el-row :gutter="16" style="margin-top: 16px;">
        <el-col :span="4">
          <el-card
            class="type-card compact"
            :class="{ active: activeType === 'personal' }"
            @click="setActiveType('personal')"
            shadow="hover"
          >
            <div class="type-content">
              <el-icon class="type-icon"><User /></el-icon>
              <h4>个人偏好</h4>
              <p>基于穿搭习惯</p>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- AI服务选择 -->
      <el-card class="ai-provider-card" v-if="activeType === 'ai'" style="margin-top: 16px;">
        <template #header>
          <span>选择AI服务</span>
        </template>

        <el-radio-group v-model="selectedAIProvider" @change="changeAIProvider">
          <el-radio label="local">本地AI（免费）</el-radio>
          <el-radio label="qianwen">通义千问（免费额度）</el-radio>
          <el-radio label="deepseek">DeepSeek（免费额度）</el-radio>
          <el-radio label="doubao">豆包（免费额度）</el-radio>
          <el-radio label="vapi">V-API聚合（多模型）</el-radio>
        </el-radio-group>

        <div class="ai-provider-info" v-if="selectedAIProvider !== 'local'">
          <el-alert
            :title="getAIProviderInfo(selectedAIProvider).title"
            :description="getAIProviderInfo(selectedAIProvider).description"
            type="info"
            :closable="false"
            show-icon
          />
        </div>
      </el-card>
    </el-card>

    <!-- 推荐参数设置 -->
    <el-card class="recommendation-params" v-if="activeType">
      <template #header>
        <span>推荐参数</span>
      </template>

      <!-- 天气推荐参数 -->
      <div v-if="activeType === 'weather'" class="weather-params">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="天气状况">
              <el-select v-model="weatherParams.weather" placeholder="选择天气">
                <el-option label="晴天" value="sunny" />
                <el-option label="多云" value="cloudy" />
                <el-option label="雨天" value="rainy" />
                <el-option label="雪天" value="snowy" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="温度">
              <el-input-number
                v-model="weatherParams.temperature"
                :min="-20"
                :max="50"
                placeholder="温度"
              />
              <span style="margin-left: 8px;">°C</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="地点">
              <el-input v-model="weatherParams.location" placeholder="城市" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 场合推荐参数 -->
      <div v-if="activeType === 'occasion'" class="occasion-params">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="场合">
              <el-select v-model="occasionParams.occasion" placeholder="选择场合">
                <el-option label="工作" value="work" />
                <el-option label="休闲" value="casual" />
                <el-option label="正式" value="formal" />
                <el-option label="派对" value="party" />
                <el-option label="约会" value="date" />
                <el-option label="运动" value="sport" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="风格偏好">
              <el-select v-model="occasionParams.style" placeholder="选择风格">
                <el-option label="商务" value="business" />
                <el-option label="休闲" value="casual" />
                <el-option label="优雅" value="elegant" />
                <el-option label="时尚" value="trendy" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 颜色推荐参数 -->
      <div v-if="activeType === 'color'" class="color-params">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="基础颜色">
              <el-color-picker v-model="colorParams.baseColor" />
              <el-input
                v-model="colorParams.baseColor"
                placeholder="颜色名称或HEX值"
                style="width: 200px; margin-left: 10px;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="配色方案">
              <el-select v-model="colorParams.colorScheme" placeholder="选择配色方案">
                <el-option label="互补色" value="complementary" />
                <el-option label="类似色" value="analogous" />
                <el-option label="三角色" value="triadic" />
                <el-option label="单色系" value="monochromatic" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <el-button
        type="primary"
        @click="getRecommendations"
        :loading="loading"
        size="large"
      >
        <el-icon><MagicStick /></el-icon>
        获取推荐
      </el-button>

      <el-button
        @click="testAPI"
        type="warning"
        size="small"
        style="margin-left: 10px;"
      >
        测试API
      </el-button>

      <el-button
        @click="testAI"
        type="success"
        size="small"
        style="margin-left: 10px;"
      >
        测试AI
      </el-button>

      <el-button
        @click="testLocalAI"
        type="info"
        size="small"
        style="margin-left: 10px;"
      >
        测试本地AI
      </el-button>

      <el-button
        @click="checkAIStatus"
        type="primary"
        size="small"
        style="margin-left: 10px;"
      >
        检查AI状态
      </el-button>
    </el-card>

    <!-- 推荐结果 -->
    <el-card class="recommendation-results" v-if="recommendations.length > 0">
      <template #header>
        <div class="results-header">
          <span>推荐结果</span>
          <el-tag type="success">{{ recommendations.length }} 个推荐</el-tag>
        </div>
      </template>

      <!-- 推荐统计信息 -->
      <div v-if="analysisData" class="analysis-summary" style="margin-bottom: 20px;">
        <el-alert
          :title="`共获取到 ${recommendations.length} 个推荐搭配`"
          type="success"
          :closable="false"
          show-icon
        >
          <template #default>
            <p>天气推荐: {{ analysisData.weatherBased }} 套，个人偏好: {{ analysisData.personalBased }} 套，场合推荐: {{ analysisData.occasionBased }} 套</p>
          </template>
        </el-alert>
      </div>

      <div class="recommendations-grid">
        <div
          v-for="(recommendation, index) in recommendations"
          :key="index"
          class="recommendation-item"
        >
          <el-card shadow="hover">
            <div class="recommendation-content">
              <!-- 推荐标题 -->
              <div class="recommendation-header">
                <h4>推荐搭配 {{ index + 1 }}</h4>
                <div class="recommendation-reason" v-if="recommendation.reason">
                  <el-tag size="small" type="info">{{ recommendation.reason }}</el-tag>
                </div>
              </div>

              <!-- 衣服展示 -->
              <div class="recommendation-images">
                <!-- 购买建议特殊显示 -->
                <div v-if="recommendation.isShoppingSuggestion" class="shopping-suggestion">
                  <el-icon class="shopping-icon" size="48"><ShoppingBag /></el-icon>
                  <p>您的衣柜还没有衣服</p>
                  <p><small>请先添加一些衣服，AI就能为您生成个性化搭配了</small></p>
                </div>

                <!-- 真实衣柜搭配显示 -->
                <div v-else-if="recommendation.isRealClothing && recommendation.items && recommendation.items.length > 0" class="real-clothing-outfit">
                  <div class="outfit-badge">
                    <el-tag type="success" size="small">
                      <el-icon><Star /></el-icon>
                      基于您的衣柜
                    </el-tag>
                  </div>
                  <div class="clothing-grid">
                    <div
                      v-for="item in recommendation.items"
                      :key="item.id"
                      class="clothing-item real-item"
                    >
                      <el-image
                        :src="item.main_image || '/placeholder-clothing.png'"
                        :alt="item.name"
                        fit="cover"
                        class="clothing-image"
                      />
                      <div class="clothing-info">
                        <span class="clothing-name">{{ item.name }}</span>
                        <span class="clothing-details">{{ item.color }} | {{ item.category?.name }}</span>
                        <span class="clothing-id">ID: {{ item.id }}</span>
                      </div>
                    </div>
                  </div>
                </div>

                <!-- 普通推荐显示 -->
                <div v-else-if="recommendation.items && recommendation.items.length > 0" class="normal-recommendation">
                  <div
                    v-for="item in recommendation.items"
                    :key="item.id"
                    class="clothing-item"
                  >
                    <el-image
                      :src="item.main_image || '/placeholder-clothing.png'"
                      :alt="item.name"
                      fit="cover"
                      class="clothing-image"
                    />
                    <span class="clothing-name">{{ item.name }}</span>
                  </div>
                </div>

                <!-- 无衣服信息 -->
                <div v-else class="no-items">
                  <p>暂无衣服信息</p>
                  <p><small>clothingIds: {{ recommendation.clothingIds }}</small></p>
                </div>
              </div>

              <div class="recommendation-info">
                <div class="score">
                  <span class="score-label">匹配度：</span>
                  <el-rate
                    :model-value="recommendation.score"
                    :max="1"
                    show-score
                    disabled
                    text-color="#ff9900"
                  />
                  <span class="score-text">{{ Math.round(recommendation.score * 100) }}%</span>
                </div>

                <div class="tags">
                  <el-tag
                    v-for="tag in recommendation.tags"
                    :key="tag"
                    size="small"
                    style="margin-right: 5px;"
                  >
                    {{ tag }}
                  </el-tag>
                </div>

                <div class="actions">
                  <el-button size="small" @click="saveAsOutfit(recommendation)">
                    保存为搭配
                  </el-button>
                  <el-button size="small" @click="provideFeedback(recommendation, index)">
                    反馈
                  </el-button>
                </div>
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </el-card>

    <!-- 反馈对话框 -->
    <el-dialog v-model="feedbackDialogVisible" title="推荐反馈" width="500px">
      <el-form :model="feedbackForm" label-width="80px">
        <el-form-item label="评分">
          <el-rate v-model="feedbackForm.rating" />
        </el-form-item>
        <el-form-item label="反馈">
          <el-radio-group v-model="feedbackForm.feedback">
            <el-radio label="like">喜欢</el-radio>
            <el-radio label="dislike">不喜欢</el-radio>
            <el-radio label="neutral">一般</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="评论">
          <el-input
            v-model="feedbackForm.comment"
            type="textarea"
            :rows="3"
            placeholder="请分享您的想法..."
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="feedbackDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitFeedback">提交反馈</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { recommendationAPI, outfitAPI } from '@/api'
import localAI from '@/utils/localAI'
import { useLocation } from '@/composables/useLocation'
import LocationStatus from '@/components/LocationStatus.vue'

// 响应式数据
const activeType = ref('smart')
const loading = ref(false)
const recommendations = ref([])
const feedbackDialogVisible = ref(false)
const currentRecommendationIndex = ref(-1)
const weatherInfo = ref(null)
const weatherLoading = ref(false)
const selectedCity = ref('北京')
const analysisData = ref(null)
const selectedAIProvider = ref('local')

// 使用地理位置组合式API
const {
  location: userLocation,
  loading: locationLoading,
  error: locationError,
  locationParams,
  getCurrentLocation,
  refreshLocation
} = useLocation({ autoLoad: false, showMessage: true })

// 计算当前城市
const currentCity = computed(() => {
  return userLocation.value?.city || selectedCity.value
})

// 推荐参数
const weatherParams = reactive({
  weather: '',
  temperature: 20,
  location: ''
})

const occasionParams = reactive({
  occasion: '',
  style: ''
})

const colorParams = reactive({
  baseColor: '#409EFF',
  colorScheme: 'complementary'
})

// 反馈表单
const feedbackForm = reactive({
  rating: 0,
  feedback: '',
  comment: ''
})

// 天气相关方法
const loadWeatherInfo = async () => {
  weatherLoading.value = true
  try {
    // 使用地理位置参数获取天气
    const response = await recommendationAPI.getWeatherInfo(locationParams.value)
    weatherInfo.value = response.data

    // 更新选中的城市
    if (weatherInfo.value.city) {
      selectedCity.value = weatherInfo.value.city
    }
  } catch (error) {
    console.error('获取天气信息失败:', error)
    ElMessage.error('获取天气信息失败')
  } finally {
    weatherLoading.value = false
  }
}

const refreshWeather = () => {
  loadWeatherInfo()
}

// 处理位置刷新
const handleLocationRefresh = async () => {
  try {
    await refreshLocation()
    // 位置更新后，重新获取天气信息
    await loadWeatherInfo()
  } catch (error) {
    console.error('刷新位置失败:', error)
  }
}

// 设置活动类型
const setActiveType = (type) => {
  activeType.value = type
  recommendations.value = []
}

// 测试API
const testAPI = async () => {
  try {
    console.log('开始测试API...')

    // 测试天气API
    const weatherResponse = await recommendationAPI.getWeatherInfo('北京')
    console.log('天气API响应:', weatherResponse)

    // 测试智能推荐API
    const smartResponse = await recommendationAPI.getSmartRecommendations({
      city: '北京',
      includeWeather: true
    })
    console.log('智能推荐API响应:', smartResponse)

    ElMessage.success('API测试完成，请查看控制台')
  } catch (error) {
    console.error('API测试失败:', error)
    ElMessage.error('API测试失败: ' + error.message)
  }
}

// 测试AI功能
const testAI = async () => {
  try {
    console.log('开始测试AI功能...')

    // 测试AI风格分析
    const aiResponse = await recommendationAPI.getAIStyleAnalysis()
    console.log('AI风格分析响应:', aiResponse)

    // 测试AI智能推荐
    const smartResponse = await recommendationAPI.getSmartRecommendations({
      city: '北京',
      includeWeather: true,
      useAI: true
    })
    console.log('AI智能推荐响应:', smartResponse)

    ElMessage.success('AI测试完成，请查看控制台')
  } catch (error) {
    console.error('AI测试失败:', error)
    ElMessage.error('AI测试失败: ' + error.message)
  }
}

// 测试本地AI功能
const testLocalAI = async () => {
  try {
    console.log('开始测试本地AI功能...')

    // 初始化本地AI
    const initialized = await localAI.initialize()
    console.log('本地AI初始化结果:', initialized)

    // 测试颜色搭配分析
    const colorAnalysis = await localAI.analyzeColorMatching('#FF0000')
    console.log('颜色搭配分析:', colorAnalysis)

    // 测试风格分析
    const styleAnalysis = await localAI.analyzeStyle({
      category: '上装',
      color: '#0000FF',
      style: '休闲'
    })
    console.log('风格分析:', styleAnalysis)

    // 测试智能推荐
    const outfitRec = await localAI.generateOutfitRecommendation(
      { preferredStyle: '休闲', favoriteColors: ['#FF0000'] },
      { temperature: 20, condition: '晴' },
      []
    )
    console.log('智能推荐:', outfitRec)

    ElMessage.success('本地AI测试完成，请查看控制台')
  } catch (error) {
    console.error('本地AI测试失败:', error)
    ElMessage.error('本地AI测试失败: ' + error.message)
  }
}

// 切换AI服务提供商
const changeAIProvider = (provider) => {
  console.log('切换AI服务提供商:', provider)
  selectedAIProvider.value = provider
}

// 获取AI服务提供商信息
const getAIProviderInfo = (provider) => {
  const infoMap = {
    qianwen: {
      title: '通义千问 - 阿里云',
      description: '免费额度：每月100万tokens，需要在阿里云控制台申请API密钥'
    },
    deepseek: {
      title: 'DeepSeek - 深度求索',
      description: '免费额度：每月500万tokens，注册即可获得API密钥'
    },
    doubao: {
      title: '豆包 - 火山引擎',
      description: '免费额度：每月100万tokens，字节跳动旗下AI服务'
    },
    vapi: {
      title: 'V-API - 聚合服务',
      description: '多模型聚合平台，支持GPT、Claude等多种模型'
    }
  }

  return infoMap[provider] || { title: '', description: '' }
}

// 检查AI服务状态
const checkAIStatus = async () => {
  try {
    console.log('检查AI服务状态...')

    const response = await recommendationAPI.checkAIStatus()
    console.log('AI服务状态:', response.data)

    const status = response.data
    let message = `当前AI服务: ${status.provider}\n`
    message += `状态: ${status.available ? '可用' : '不可用'}\n`
    message += `信息: ${status.message}\n\n`
    message += '各服务状态:\n'

    Object.keys(status.services).forEach(service => {
      const serviceStatus = status.services[service]
      message += `${service}: ${serviceStatus.available ? '✅' : '❌'} ${serviceStatus.message}\n`
    })

    ElMessageBox.alert(message, 'AI服务状态', {
      confirmButtonText: '确定',
      type: status.available ? 'success' : 'warning'
    })

  } catch (error) {
    console.error('检查AI状态失败:', error)
    ElMessage.error('检查AI状态失败: ' + error.message)
  }
}

// 获取推荐
const getRecommendations = async () => {
  try {
    loading.value = true
    let response

    switch (activeType.value) {
      case 'smart':
        response = await recommendationAPI.getSmartRecommendations({
          ...locationParams.value,
          includeWeather: true
        })
        analysisData.value = response.data.analysis
        break
      case 'today':
        response = await recommendationAPI.getTodayRecommendations(locationParams.value)
        break
      case 'weather':
        response = await recommendationAPI.getWeatherBased({
          ...weatherParams,
          ...locationParams.value
        })
        break
      case 'occasion':
        response = await recommendationAPI.getOccasionBased({
          ...occasionParams,
          ...locationParams.value
        })
        break
      case 'color':
        response = await recommendationAPI.getColorBased({
          ...colorParams,
          ...locationParams.value
        })
        break
      case 'personal':
        response = await recommendationAPI.getPersonalBased(locationParams.value)
        break
      case 'ai':
        // 使用智能推荐接口，启用AI分析
        response = await recommendationAPI.getSmartRecommendations({
          ...locationParams.value,
          includeWeather: true,
          useAI: true // 强制启用AI
        })
        break
    }

    if (response.code === 200) {
      // 处理不同API返回的数据结构
      let recs = response.data.recommendations || response.data.list || response.data || []

      // 确保每个推荐都有正确的数据结构
      recommendations.value = recs.map(rec => ({
        ...rec,
        items: rec.items || [],
        clothingIds: rec.clothingIds || [],
        score: rec.score || 0.5,
        tags: rec.tags || [],
        reason: rec.reason || rec.recommendReason || '为您推荐'
      }))

      console.log('处理后的推荐数据:', recommendations.value)
      ElMessage.success(`获取到 ${recommendations.value.length} 个推荐`)
    } else {
      throw new Error(response.message || '获取推荐失败')
    }
  } catch (error) {
    console.error('获取推荐失败:', error)
    ElMessage.error('获取推荐失败')
  } finally {
    loading.value = false
  }
}

// 保存为搭配
const saveAsOutfit = async (recommendation) => {
  try {
    const clothingIds = recommendation.clothingIds || recommendation.items?.map(item => item.id) || []

    if (clothingIds.length === 0) {
      ElMessage.warning('该推荐没有包含衣服信息')
      return
    }

    // 弹出输入框让用户输入搭配名称
    const { value: outfitName } = await ElMessageBox.prompt('请输入搭配名称', '保存搭配', {
      confirmButtonText: '保存',
      cancelButtonText: '取消',
      inputPattern: /.+/,
      inputErrorMessage: '搭配名称不能为空'
    })

    // 调用创建搭配的API
    await outfitAPI.create({
      name: outfitName,
      description: recommendation.reason || '来自智能推荐',
      clothing_ids: clothingIds
    })

    ElMessage.success('搭配保存成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('保存搭配失败:', error)
      ElMessage.error('保存搭配失败，请稍后重试')
    }
  }
}

// 提供反馈
const provideFeedback = (recommendation, index) => {
  currentRecommendationIndex.value = index
  feedbackForm.rating = 0
  feedbackForm.feedback = ''
  feedbackForm.comment = ''
  feedbackDialogVisible.value = true
}

// 提交反馈
const submitFeedback = async () => {
  try {
    await recommendationAPI.recordFeedback({
      recommendationId: recommendations.value[currentRecommendationIndex.value].id,
      feedback: feedbackForm.feedback,
      rating: feedbackForm.rating,
      comment: feedbackForm.comment
    })

    ElMessage.success('反馈提交成功')
    feedbackDialogVisible.value = false
  } catch (error) {
    console.error('提交反馈失败:', error)
    ElMessage.error('提交反馈失败')
  }
}

// 页面初始化
onMounted(async () => {
  // 检查认证状态
  const token = localStorage.getItem('token')
  console.log('Current token:', token)
  if (!token) {
    ElMessage.warning('请先登录')
    // 可以跳转到登录页面
  }

  // 自动获取用户位置
  try {
    console.log('🌍 开始获取用户位置...')
    const locationData = await getCurrentLocation()

    if (locationData) {
      console.log('📍 位置获取成功:', {
        city: locationData.city,
        province: locationData.province,
        district: locationData.district,
        address: locationData.address,
        coordinates: `${locationData.latitude}, ${locationData.longitude}`,
        source: locationData.source,
        accuracy: locationData.accuracy
      })

      // 更新选中的城市
      selectedCity.value = locationData.city || '北京'

      // 位置获取成功后，自动加载天气信息
      console.log('🌤️ 开始获取天气信息...')
      await loadWeatherInfo()
    }
  } catch (error) {
    console.error('❌ 初始化位置信息失败:', error)
    // 即使位置获取失败，也尝试加载默认天气
    await loadWeatherInfo()
  }

  // 移除自动获取推荐，等待用户主动选择
  console.log('✅ 初始化完成，等待用户选择推荐类型...')
})
</script>

<script>
export default {
  components: {
    LocationStatus
  }
}
</script>

<style scoped>
.recommendation-view {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

/* 天气卡片样式 */
.weather-card {
  margin-bottom: 20px;
}

.weather-header {
  display: flex;
  align-items: center;
  gap: 10px;
}

.weather-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.weather-main {
  text-align: center;
}

.temperature {
  font-size: 48px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.condition {
  font-size: 18px;
  color: #303133;
  margin-bottom: 5px;
}

.feels-like {
  font-size: 14px;
  color: #909399;
}

.weather-details {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  min-width: 120px;
}

.detail-item .label {
  color: #909399;
}

.detail-item .value {
  color: #303133;
  font-weight: 500;
}

.weather-mock {
  margin-top: 15px;
}

/* 真实衣柜推荐样式 */
.shopping-suggestion {
  text-align: center;
  padding: 40px 20px;
  background: #f8f9fa;
  border-radius: 8px;
  color: #666;
}

.shopping-icon {
  color: #409eff;
  margin-bottom: 15px;
}

.real-clothing-outfit {
  position: relative;
}

.outfit-badge {
  position: absolute;
  top: -10px;
  right: -10px;
  z-index: 10;
}

.clothing-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
  gap: 12px;
  margin-top: 10px;
}

.real-item {
  border: 2px solid #67c23a;
  border-radius: 8px;
  padding: 8px;
  background: #f0f9ff;
}

.clothing-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
  margin-top: 5px;
}

.clothing-details {
  font-size: 12px;
  color: #909399;
}

.clothing-id {
  font-size: 10px;
  color: #67c23a;
  font-weight: bold;
}

.normal-recommendation {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
  gap: 12px;
  margin-top: 10px;
}

/* 调试信息样式 */
.debug-info {
  font-size: 12px;
  color: #666;
}

/* 推荐展示样式 */
.recommendation-header {
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.recommendation-header h4 {
  margin: 0;
  color: #303133;
}

.recommendation-reason {
  margin-left: 10px;
}

.no-items {
  text-align: center;
  color: #909399;
  padding: 20px;
  background: #f5f5f5;
  border-radius: 4px;
}

.score {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.score-label {
  font-size: 14px;
  color: #606266;
}

.score-text {
  font-size: 14px;
  color: #409eff;
  font-weight: 500;
}

.recommendation-types {
  margin-bottom: 20px;
}

.type-card {
  cursor: pointer;
  transition: all 0.3s;
  height: 120px;
}

.type-card.compact {
  height: 90px;
}

.type-card:hover {
  transform: translateY(-2px);
}

.type-card.active {
  border-color: #409EFF;
  box-shadow: 0 2px 12px rgba(64, 158, 255, 0.3);
}

.type-content {
  text-align: center;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.type-card.compact .type-content {
  padding: 8px 4px;
}

.type-icon {
  font-size: 24px;
  color: #409EFF;
  margin-bottom: 8px;
}

.type-card.compact .type-icon {
  font-size: 20px;
  margin-bottom: 4px;
}

.type-content h4 {
  margin: 8px 0 4px 0;
  font-size: 16px;
  color: #333;
}

.type-card.compact .type-content h4 {
  margin: 4px 0 2px 0;
  font-size: 14px;
}

.type-content p {
  margin: 0;
  font-size: 12px;
  color: #666;
}

.type-card.compact .type-content p {
  font-size: 11px;
  line-height: 1.2;
}

.recommendation-params {
  margin-bottom: 20px;
}

.recommendation-results {
  margin-bottom: 20px;
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.recommendations-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
}

.recommendation-item {
  width: 100%;
}

.recommendation-content {
  padding: 14px;
}

.recommendation-images {
  margin-bottom: 12px;
}

.clothing-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-width: 80px;
  max-width: 120px;
}

.clothing-image {
  width: 70px;
  height: 70px;
  object-fit: cover;
  border-radius: 8px;
  border: 1px solid #eee;
}

.clothing-name {
  font-size: 11px;
  color: #666;
  text-align: center;
  margin-top: 4px;
  word-break: break-all;
  line-height: 1.2;
  max-height: 2.4em;
  overflow: hidden;
}

.recommendation-info {
  border-top: 1px solid #eee;
  padding-top: 16px;
}

.score {
  margin-bottom: 8px;
}

.tags {
  margin-bottom: 12px;
}

.actions {
  display: flex;
  gap: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .recommendation-view {
    padding: 16px;
  }

  .recommendations-grid {
    grid-template-columns: 1fr;
  }

  .type-card {
    height: 100px;
  }

  .type-content h4 {
    font-size: 14px;
  }

  .type-content p {
    font-size: 11px;
  }
}
</style>
